package com.aboverock.module.system.validator.constraintvalidators;

import com.aboverock.common.helper.MetadataHelper;
import com.aboverock.core.spring.SpringContextHolder;
import com.aboverock.module.system.service.ValidatorService;
import com.aboverock.module.system.validator.constraints.UniqueFields;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.util.ReflectionUtils;

/**
 * The Class UniqueLoginNameValidator.
 *
 * @author Rock Wang
 */
public class UniqueFieldsValidator implements ConstraintValidator<UniqueFields, Object> {

    private Class<?> clazz;
    private String[] fields;

    @Override
    public void initialize(UniqueFields constraintAnnotation) {
        clazz = constraintAnnotation.clazz();
        fields = constraintAnnotation.fields();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        if (0 == fields.length) {
            return true;
        }

        String[] columnNames = MetadataHelper.convertVariable2Column(clazz, fields);
        Map<String, Object> conditions = new HashMap<>(16);
        for (int i = 0; i < fields.length; i++) {
            Field field = ReflectionUtils.findField(clazz, fields[i]);
            ReflectionUtils.makeAccessible(field);
            Object value = ReflectionUtils.getField(field, object);
            if (null == value) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(
                        "{javax.validation.constraints.NotNull.message}").addConstraintViolation();
                return false;
            }
            conditions.put(columnNames[i], value);
        }

        Field field = ReflectionUtils.findField(clazz, "id");
        ReflectionUtils.makeAccessible(field);
        Object id = ReflectionUtils.getField(field, object);

        ValidatorService service = SpringContextHolder.getBean(ValidatorService.class);
        String tableName = MetadataHelper.getTableName(clazz);
        int dataNum = service.selectCount(tableName, conditions, id);
        
        if (0 == dataNum) {
            return true;
        }

        return false;
    }
}
